package com.sky;

import com.alibaba.fastjson.JSONObject;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
@Slf4j
public class BaiduUtil {
    //可以设置为自己百度应用的ak
    private static String ak = "DtQLu0aDGqPzyUTqGxuALWAUHbrxPcH4";
    //骑行路线规划
    private static String url1 = "https://api.map.baidu.com/directionlite/v1/riding";
    //获取地址对应经纬度
    private static String url2 = "https://api.map.baidu.com/geocoding/v3/";

    /**
     *
     * @param origin 起点
     * @param destination 终点
     * @return 距离
     */
    public static long getDistance(String origin, String destination) {
        Map<String, String> map = new HashMap<>();
        map.put("origin", getLongitudeAndLatitude(origin));
        map.put("destination", getLongitudeAndLatitude(destination));
        map.put("riding_type", "1");
        map.put("ak", ak);
        String data = HttpClientUtil.doGet(url1, map);
        System.out.println("data = " + data);
        log.error("=============");
        return  JSONObject
                .parseObject(data)
                .getJSONObject("result")
                .getJSONArray("routes")
                .stream()
                .map(obj->JSONObject.parseObject(obj.toString()))
                .min((o1, o2) -> Integer.compare(o1.getInteger("distance"),o2.getInteger("distance")))
                .get()
                .getLong("distance");

    }


    //获取一个地址的经纬度
    public static String getLongitudeAndLatitude(String address) {
        Map<String, String> map = new HashMap<>();
        map.put("address", address);
        map.put("output", "json");
        map.put("ak", ak);
        String data = HttpClientUtil.doGet(url2, map);
        /*
        {
            "status": 0,
            "result": {
                "location": {
                    "lng": 121.61932912757078,
                    "lat": 31.04135479189867
                },
                "precise": 1,
                "confidence": 80,
                "comprehension": 100,
                "level": "门址"
            }
        }
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject location = result.getJSONObject("location");
        //39.936404,116.452562
        //121.619331,31.041355
        String lanAndLat = String.format("%.6f", location.getFloat("lat"))
                + "," +
                String.format("%.6f", location.getFloat("lng"));
        System.out.println(address + " = " + lanAndLat);
        return lanAndLat;

    }
}
